/*
 * 存放查询条件中select标签的值，以select标签name为外层key，以option的value为内层key；
 * eg: selectTagMap = {status:{WU:'无'}}
 * 该对象用于匹配列表中状态等字段代码
 */
var r20 = /%20/g;
var selectTagMap = {};
var exportState = false;
$(function() {
	//获取所有select值
	$("select").each(function(){
		var optionMap = {};
		$(this).find("option").each(function(n,v){
			optionMap[v.value] = v.text;
		});
		selectTagMap[this.name] = optionMap;
	});
	//隐藏或展开查询条件
	$(".open-close").click(function(){
		var thiz = $(this).find("i");
		$("#searchForm").slideToggle(500,function(){
			if(thiz.attr("class") == "fa-chevron-up"){
				thiz.removeClass();
				thiz.addClass("fa-chevron-down");
			} else {
				thiz.removeClass();
				thiz.addClass("fa-chevron-up");
			}
		});
	});
	$("#distStatus").change(function(){
		refreshTableData();
		if(this.value == 'UNDISTED') {
			$(".show-ctrl").show();
			$(".show-ctrl2").hide();
		}else if(this.value == 'DISTED'){
			$(".show-ctrl").hide();
			$(".show-ctrl2").show();
		}else {
			$(".show-ctrl").hide();
			$(".show-ctrl2").hide();
		}
	});
	//add by jief 2016-09-11 start
	$("#dateVisitOption").change(function(){
		if(this.value == '2') {
			$("#dateVisitEndDate").show();
		}else {
			$("#dateVisitEndDate").hide();
		}
	});
	$("#dateAppointmentOption").change(function(){
		if(this.value == '2') {
			$("#dateAppointmentEndDate").show();
		}else {
			$("#dateAppointmentEndDate").hide();
		}
	});
	$("#distDateOption").change(function(){
		if(this.value == '2') {
			$("#distDateEndDate").show();
		}else {
			$("#distDateEndDate").hide();
		}
	});
	//add by jief 2016-09-11 end 
	
	//初始化表格
    $("#contentTable").bootstrapTable($.fn.BTConfigSimple({
    	pageSize: 20,
    	pageList: [10, 20, 50, 200, 400, 500, 1000],
    	sortName: "a.lastUpdated",
    	sortOrder: "desc",
    	userQuery:function(){
            return $('#searchForm').refreshByForm().query;
        }
    }));
	//初始化模态框
    $('#distModal').modal({
    	backdrop:'static',
    	show: false,
    	keyboard: false
    });
    //初始化模态框
    $('#groupModal').modal({
    	backdrop:'static',
    	show: false,
    	keyboard: false
    });
    //初始化模态框
    $('#batchEditModal').modal({
    	backdrop:'static',
    	show: false,
    	keyboard: false
    });
  //初始化模态框
    $('#mergerModal').modal({
    	backdrop:'static',
    	show: false,
    	keyboard: false
    });
	//分配弹出框
	$("#aDist").click(function(){
		if (!$("#contentTable").bootstrapTable('getSelections').length) {
			alertx("请选择需要分配的数据！");
			return false;
		}
		$("#distPage").attr("src",$(this).data("url"));
		$("#distModal").modal("show");
		return false;
	});
	//分配
	$("#btnDist").click(function(){
		var dist_url = $(this).data("url");
		var userIds = window.frames["distPage"].selectUser();
		if (!userIds) {
			alertx("请选择需要分配的人员！");
			return false;
		}
		var ids = $.map($("#contentTable").bootstrapTable('getSelections'), function (row) {
            return row.id;
        });
		$.ajax({
			url:dist_url,
			type : "POST",
			data: {userIds: userIds.join(','),ids: ids.join(',')},
			dataType: "json",
			success : function(data){
				if (data.state) {
					alertx(data.message,function(){
						$("#distModal").modal("hide");
						refreshTableData();
					},null,null,"info");
				} else {
					alertx(data.message,function(){
						$("#distModal").modal("hide");
						refreshTableData();
					},null,null,"error");
				}
			},
			error: function(){
				alertx("发送请求失败，请稍后再试！",function(){
					$("#distModal").modal("hide");
					refreshTableData();
				},null,null,"error");
			}
		});
	});
	
	//分组弹出框
	$("#aGroup").click(function(){
		if (!$("#contentTable").bootstrapTable('getSelections').length) {
			alertx("请选择需要分组的数据！");
			return false;
		}
		$("#groupPage").attr("src",$(this).data("url"));
		$("#groupModal").modal("show");
		return false;
	});
	
	//分组
	$("#btnGroup").click(function(){
		var group_url = $(this).data("url");
		var groupId = window.frames["groupPage"].selectGroup();
		if (!groupId) {
			alertx("请选择分组！");
			return false;
		}
		var ids = $.map($("#contentTable").bootstrapTable('getSelections'), function (row) {
            return row.id;
        });
		$.ajax({
			url: group_url,
			type : "POST",
			data: {groupId: groupId,ids: ids.join(',')},
			dataType: "json",
			success : function(data){
				if (data.state) {
					alertx(data.message,function(){
						$("#groupModal").modal("hide");
						refreshTableData();
					},null,null,"info");
				} else {
					alertx(data.message,function(){
						$("#groupModal").modal("hide");
						refreshTableData();
					},null,null,"error");
				}
			},
			error: function(){
				alertx("发送请求失败，请稍后再试！",function(){
					$("#groupModal").modal("hide");
					refreshTableData();
				},null,null,"error");
			}
		});
	});
	
	//合并弹出框
	$("#aMerger").click(function(){
		var selectRows = $("#contentTable").bootstrapTable('getSelections');
		if (!selectRows.length) {
			alertx("请选择需要合并的数据！");
			return false;
		} else if (selectRows.length == 1) {
			alertx("至少选择2条数据才能进行合并操作！");
			return false;
		}
		$("#mergerTable").bootstrapTable({
			pagination : false,
            rowStyle: {classes: 'list', height: 20}
		});
		var data = $.extend([],selectRows);
		$("#mergerModal").on("show",function(){
			$("#mergerTable").bootstrapTable('removeAll');
			$("#mergerTable").bootstrapTable('load',data);
			$("#mergerTable").bootstrapTable('uncheckAll');
		});
		$("#mergerModal").modal("show");
		return false;
	});
	
	//合并
	$("#btnMerger").click(function(){
		var merger_url = $(this).data("url");
		var id = $("#mergerTable").bootstrapTable('getSelections')[0].id;
		var allData = $("#mergerTable").bootstrapTable('getData');
		var ids = new Array(),mergerNum = 0,noReadMergerNum = 0 ;
		for ( var i = 0 ; i < allData.length ; i ++ ) {
			var _data = allData[i];
			ids.push(_data.id);
			mergerNum += _data.mergerNum;//统计合并数量
			noReadMergerNum += _data.noReadMergerNum;//统计未读数量
		}
		mergerNum = mergerNum + (allData.length -1);//加上被合并的数据条数
		ids.splice(ids.indexOf(id), 1);  //去掉选择的ID
		$.ajax({
			url: merger_url,
			type : "POST",
			data : {id: id,mergerNum: mergerNum,noReadMergerNum: noReadMergerNum,ids: ids.join(',')},
			dataType: "json",
			success : function(data){
				if (data.state) {
					alertx(data.message,function(){
						$("#mergerModal").modal("hide");
						refreshTableData();
					},null,null,"info");
				} else {
					alertx(data.message,function(){
						$("#mergerModal").modal("hide");
						refreshTableData();
					},null,null,"error");
				}
			},
			error: function(){
				alertx("发送请求失败，请稍后再试！",function(){
					$("#mergerModal").modal("hide");
					refreshTableData();
				},null,null,"error");
			}
		});
	});
	
	//批量修改弹出框
	$("#aBatchEdit").click(function(){
		if (!$("#contentTable").bootstrapTable('getSelections').length) {
			alertx("请选择修改的数据！");
			return false;
		}
		$("#batchEditPage").attr("src",$(this).data("url"));
		$("#batchEditModal").modal("show");
		return false;
	});
	
	//批量修改
	$("#btnbatchEdit").click(function(){
		var batch_edit_url = $(this).data("editurl");
		var formsData = window.frames["batchEditPage"].getFormsData();
		if (!formsData) return;
		var ids = $.map($("#contentTable").bootstrapTable('getSelections'), function (row) {
			return row.id;
		}).join(",");
		var params =new Array();
		params[0]= formsData;
		params[1]= $.param({"customer.ids":ids});
		var postParams = params.join("&").replace( r20, "+" );
		$.ajax({
			url: batch_edit_url,
			type : "POST",
			data: postParams,
			dataType: "json",
			success : function(data){
				if (data.state) {
					alertx(data.message,function(){
						$("#batchEditModal").modal("hide");
						refreshTableData();
					},null,null,"info");
				} else {
					alertx(data.message,function(){
						$("#batchEditModal").modal("hide");
						refreshTableData();
					},null,null,"error");
				}
			},
			error: function(){
				alertx("发送请求失败，请稍后再试！",function(){
					$("#batchEditModal").modal("hide");
					refreshTableData();
				},null,null,"error");
			}
		});
	});
	//回收 add jief 2016-09-08
	$("#aRecovery").click(function(){
		var thiz = this;
		if (!$("#contentTable").bootstrapTable('getSelections').length) {
			alertx("请选择需要回收的数据！");
			return false;
		}
		var ids = $.map($("#contentTable").bootstrapTable('getSelections'), function (row) {
            return row.id;
        });
		confirmx("确定回收选中的数据吗？",function(){
			$.ajax({
				url: $(thiz).data("url"),
				type : "POST",
				data: {ids: ids.join(',')},
				dataType: "json",
				success : function(data){
					if (data.state) {
						alertx(data.message,function(){
							refreshTableData();
						},null,null,"info");
					} else {
						alertx(data.message,function(){
							refreshTableData();
						},null,null,"error");
					}
				},
				error: function(){
					alertx("发送请求失败，请稍后再试！",function(){
						refreshTableData();
					},null,null,"error");
				}
			});
		});
		return false;
	});
	//删除
	$("#aDel").click(function(){
		var thiz = this;
		if (!$("#contentTable").bootstrapTable('getSelections').length) {
			alertx("请选择需要删除的数据！");
			return false;
		}
		var ids = $.map($("#contentTable").bootstrapTable('getSelections'), function (row) {
            return row.id;
        });
		confirmx("确定删除选中的数据吗？",function(){
			$.ajax({
				url: $(thiz).data("url"),
				type : "POST",
				data: {ids: ids.join(',')},
				dataType: "json",
				success : function(data){
					if (data.state) {
						alertx(data.message,function(){
							refreshTableData();
						},null,null,"info");
					} else {
						alertx(data.message,function(){
							refreshTableData();
						},null,null,"error");
					}
				},
				error: function(){
					alertx("发送请求失败，请稍后再试！",function(){
						refreshTableData();
					},null,null,"error");
				}
			});
		});
		return false;
	});
	//导出
	$("#aExport").click(function(){
        var _this = this;
        var url = ctx+"/export/checkLocker.shtml?id=potentialCustomerExport";
        $.get(url,function(data){
           if(data.state){
               loading("正在导出数据(最大10000条)请稍等……");
               var form = $("#searchForm");
               var params =  form.serialize();
               var exportURL = $(_this).data("url") + '?'+params;
               window.location.href = exportURL;
               makeTimeOutExport(url,exportURL,0);
           }else{
               alertx("该表正被另外一个用户导出!为了减少服务器压力请稍后在进行导出操作!");
           }
        });
	});
	$(".addTab").live("click", function () {
        return window.parent.addTab($(this));
    });
});

function makeTimeOutExport(url,exportURL,page){
    setTimeout(function(){
        $.get(url,function(data){
            if(data.state){
                closeTip();
                /*loading("正在导出数据(最大10000条)请稍等……");
                confirmx("继续导出",function(){
                    window.location.href = exportURL+"&pageNo="+(page+1);
                    makeTimeOutExport(url,exportURL,page+1);
                });*/
            }else{
                makeTimeOutExport(url,exportURL,page);
            }
        });
    },5000);
}

function refreshTableData(){
	$("#contentTable").bootstrapTable('refresh',$('#searchForm').refreshByForm());
}

function dataStatusFormatter(value, row, index) {
	return row.mergerNum + "（<font color='red'>"+row.noReadMergerNum+"</font>）";
}

function distStatusFormatter(value, row, index) {
	if(value=='DISTED'){
		return row.executorName;
	}
	return selectTagMap["distStatus"][value];
}

function corporationNameFormatter(value, row, index) {
	var aText = new Array();
	aText.push("<a class='addTab' ");
	if (row.dateVisit) {
		if (row.customerStatusFreeze == row.customerStatusId) {
			aText.push("style='color:#51A351' ");
			aText.push("title='提示：无意向数据已解禁' ");
		}
	}
	aText.push("href='");
	aText.push(ctx);
	aText.push("/customer/potentialCustomer/detail?id=");
	aText.push(row.id);
	aText.push("' target='mainFrame'>");
	aText.push(value);
	aText.push("</a>");
	return aText.join('');
}

function targetProductsFormatter(value, row, index) {
	var _value = selectTagMap["targetProducts"][value];
	return _value ? _value : "无";
}
